<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh_CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script th:src="@{/js/jquery-3.6.0.js}"></script>
</head>
<body>
<h1>在线人数:<span id="online" style="color: red">加载中。。。</span></h1>
<div style="display: flex; width: 100%;">
    <div style="height: auto;width: 300px; border: 1px #fa8072 solid">
        <form method="post" enctype="multipart/form-data" id="imgForm">
            <input type="file" name="avatar">
            <button type="button" id="sub">上传</button>
        </form>
    <img src="" id="upImg" style="width: 100%;height: auto;">
    </div>
    <div>
        <div id="message"></div>
        <textarea id="msg"></textarea>
        <button onclick="send()">发送</button>
        <button onclick="closeWebSocket()">关闭连接</button>
    </div>
</div>
</body>


<script>
    if(sessionStorage.getItem("user")==null){
        location.href="/login"//如果session为空返回登录
    }
    let user = sessionStorage.getItem("user")
    let userId =JSON.parse(user).id
    let groupId
    if(userId==1){
        groupId="1"
    }else {
        groupId="2"
    }

    let friendId
    if(userId==1){
        friendId=6
    }else {
        friendId=1
    }



    // let groupId_userId=groupId+"-"+userId
    let groupId_userId=friendId+"_"+userId


    console.log(groupId_userId)

    let websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        //连接WebSocket节点
        websocket = new WebSocket("ws://47.97.156.3:8080/websocket/" + groupId_userId);
        // websocket = new WebSocket("ws://localhost:8080/websocket/" + groupId_userId);
    } else {
        alert('Not support websocket')
    }
    //连接发生错误的回调方法
    websocket.onerror = function () {
        //setMessageInnerHTML("error");
    };
    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        setMessageInnerHTML("连接成功");
    }
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        console.log("收到消息："+event.data)
        setMessageInnerHTML(event.data);
    }
    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("连接关闭");
    }
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    };

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        let message = $("#msg").val()
        //清空输入框
        $("#msg").val("")
        if (message.length == 0) {
            alert("请输入发送的内容")
            return;
        }
        let object = new Object();
        // object["groupId"] = groupId

        // object["userId"] = JSON.parse(sessionStorage.getItem("user")).id
        // object["userMsg"] = message;
        object["msg"] = message;
        object["myId"] = JSON.parse(sessionStorage.getItem("user")).id
        object["friendId"] = friendId
        object["sendTime"] = new Date();
        let jsonData = JSON.stringify(object);
        console.log("发出消息："+jsonData)
        websocket.send(jsonData);//websocket发送数据
    }

    $("#sub").click(function (){
        let data=new FormData($('#imgForm')[0]);
        $.ajax({
            url:"/group/imgUp",
            type: 'POST',
            data: data,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                console.log(data)
                document.getElementById('upImg').src=data.data
            },


        })

        console.log(data)
    })



    online()
    //循环执行，每隔1分钟执行一次online()
    let time=setInterval(online, 1000*60);
    function online(){
        $.ajax({
            url:"/user/onlineUsers/"+[[userId]],
            type: 'GET',
            contentType: "application/json",
            cache: false,
            success: function (data) {
                console.log(data)
                if(data.code){
                    document.getElementById('online').innerHTML=data.data
                }else {

                }

            },
            error:function (){
                clearInterval(time)
                document.getElementById('online').innerHTML=0
                console.log("error")

            }
        })
        console.log(userId)
    }


</script>

</html>